Page({
  data: {
    classes: ['计算机科学1班', '计算机科学2班', '软件工程1班'],
    currentClassIndex: 0,
    dates: [],
    currentDateIndex: 0,
    attendanceList: [],
    summary: {
      total: 0,
      present: 0,
      late: 0,
      absent: 0,
      leave: 0
    },
    isLoading: true
  },
  
  onLoad: function() {
    // 生成最近7天的日期
    this.generateDates();
    // 获取班级考勤数据
    this.fetchClassAttendance();
  },
  
  // 生成最近7天的日期
  generateDates: function() {
    const dates = [];
    const today = new Date();
    
    for (let i = 6; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(today.getDate() - i);
      
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      
      let label = '';
      if (i === 0) {
        label = '今天';
      } else if (i === 1) {
        label = '昨天';
      } else {
        label = this.getDayOfWeek(date.getDay());
      }
      
      dates.push({
        date: `${year}-${month}-${day}`,
        label: label
      });
    }
    
    this.setData({
      dates: dates,
      currentDateIndex: 6 // 默认选中今天
    });
  },
  
  // 获取星期几
  getDayOfWeek: function(day) {
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return days[day];
  },
  
  // 切换班级
  changeClass: function(e) {
    this.setData({
      currentClassIndex: e.detail.value,
      isLoading: true
    });
    this.fetchClassAttendance();
  },
  
  // 切换日期
  changeDate: function(e) {
    this.setData({
      currentDateIndex: e.detail.value,
      isLoading: true
    });
    this.fetchClassAttendance();
  },
  
  // 获取班级考勤数据
  fetchClassAttendance: function() {
    const classId = this.data.currentClassIndex + 1; // 假设班级ID从1开始
    const date = this.data.dates[this.data.currentDateIndex].date;
    
    wx.request({
      url: 'http://localhost:3000/api/attendances/class',
      method: 'GET',
      data: {
        classId: classId,
        date: date
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            attendanceList: res.data.list || [],
            summary: res.data.summary || {
              total: 0,
              present: 0,
              late: 0,
              absent: 0,
              leave: 0
            }
          });
        } else {
          wx.showToast({
            title: '获取考勤数据失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({
          isLoading: false
        });
      }
    });
  },
  
  // 导出考勤数据
  exportAttendance: function() {
    wx.showToast({
      title: '导出功能开发中',
      icon: 'none'
    });
  }
});